package com.papper.mng.dialect.tag;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.dialect.PapperDialect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.LinkedHashMap;

/**
 * @author:LaJiao
 * @date 2022年04月02日
 * @time 08时06
 * @Description:
 */
public class PaSuggestTag extends AbstractElementTagProcessor {
    private static final Logger logger   = LoggerFactory.getLogger(PaSuggestTag.class);
    // 标签名
    private static final String TAG_NAME = "suggest";

    public PaSuggestTag(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PapperDialect.PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, IElementTagStructureHandler iElementTagStructureHandler) {
        //  获取前端页面传递的属性
        String target = iProcessableElementTag.getAttributeValue("target");
        target = StringTool.isEmpty(target) ? "all" : target;
        String suggest = iProcessableElementTag.getAttributeValue("suggest");
        //  组装组件
        StringBuffer stringBuffer = new StringBuffer();
        if ("all".equalsIgnoreCase(target) || "con".equalsIgnoreCase(target)) {
            String id   = iProcessableElementTag.getAttributeValue("id");
            String name = iProcessableElementTag.getAttributeValue("name");
            name = StringTool.isEmpty(name) ? id : name;
            String value       = iProcessableElementTag.getAttributeValue("value");
            String placeholder = iProcessableElementTag.getAttributeValue("placeholder");
            String callback    = iProcessableElementTag.getAttributeValue("callback");
            // 描述信息
            stringBuffer.append("<input id='").append(id).append("' name='").append(name).append("' type='hidden' class='form-control input-sm' value='").append(value).append("'>");
            stringBuffer.append("<input id='search-").append(id).append("' type='text' class='form-control input-sm ").append(suggest).append("' value='").append(placeholder);
            stringBuffer.append("' refId='#").append(id).append("'");
            if (!StringTool.isEmpty(callback)) {
                stringBuffer.append("' callback='").append(callback).append("'");
            }
            stringBuffer.append(">");
            stringBuffer.append("<div class='input-group-btn'>");
            // 选择按钮
            stringBuffer.append("<button type='button' class='btn btn-sm btn-white dropdown-toggle' data-toggle='dropdown'>");
            stringBuffer.append("<span class='fa fa-search'></span>");
            stringBuffer.append("</button>");
            // 清空按钮
            stringBuffer.append("<button type='button' class='btn btn-sm btn-white Clear").append(suggest).append("' refObj='#search-").append(id).append("'>");
            stringBuffer.append("<span class='fa fa-remove'></span>");
            stringBuffer.append("</button>");
            // 弹出信息
            stringBuffer.append("<ul class='dropdown-menu dropdown-menu-right' role='menu'></ul>");
            stringBuffer.append("</div>");
        }
        if ("all".equalsIgnoreCase(target) || "js".equalsIgnoreCase(target)) {
            String url            = iProcessableElementTag.getAttributeValue("url");
            String allowNoKeyword = iProcessableElementTag.getAttributeValue("allowNoKeyword");
            String idField        = iProcessableElementTag.getAttributeValue("idField");
            idField = StringTool.isEmpty(idField) ? "id" : idField;
            String keyField = iProcessableElementTag.getAttributeValue("keyField");
            String attr     = iProcessableElementTag.getAttributeValue("attr");
            // 添加JS代码
            stringBuffer.append("<script>");
            stringBuffer.append("    jQuery(function ($) {");
            stringBuffer.append("        var ").append(suggest).append(" = $('.").append(suggest).append("').bsSuggest({");
            stringBuffer.append("            idField: '").append(idField).append("',");
            stringBuffer.append("            keyField: '").append(keyField).append("',");
            if (StringTool.isEmpty(allowNoKeyword)) {
                stringBuffer.append("            allowNoKeyword: true,");
            } else {
                stringBuffer.append("            allowNoKeyword: ").append(allowNoKeyword).append(",");
            }
            stringBuffer.append("            multiWord: true,");
            stringBuffer.append("            separator: ',',");
            stringBuffer.append("            getDataMethod: 'url',");
            stringBuffer.append("            effectiveFieldsAlias: {");
            if (StringTool.isEmpty(attr)) {
                stringBuffer.append("id: 'ID',");
                stringBuffer.append("code: '编号',");
                stringBuffer.append("name: '名称'");
            } else {
                LinkedHashMap attrMap = JSON.parseObject(attr, LinkedHashMap.class);
                attrMap.forEach((key, value) -> {
                    stringBuffer.append(key).append(":'").append(value).append("',");
                });
            }
            stringBuffer.append("            },");
            stringBuffer.append("            showHeader: true,");
            stringBuffer.append("            url: '").append(url).append("',");
            stringBuffer.append("            processData: function (json) {");
            stringBuffer.append("                var i, len, data = {");
            stringBuffer.append("                    value: []");
            stringBuffer.append("                };");
            stringBuffer.append("                if (!json || !json.result || json.result.length == 0) {");
            stringBuffer.append("                    return false;");
            stringBuffer.append("                }");
            stringBuffer.append("                len = json.result.length;");
            stringBuffer.append("                for (i = 0; i < len; i++) {");
            stringBuffer.append("                    data.value.push({");
            if (StringTool.isEmpty(attr)) {
                stringBuffer.append("'id': json.result[i].id,");
                stringBuffer.append("'code': json.result[i].code,");
                stringBuffer.append("'name': json.result[i].name");
            } else {
                LinkedHashMap attrMap = JSON.parseObject(attr, LinkedHashMap.class);
                attrMap.forEach((key, value) -> {
                    stringBuffer.append("'").append(key).append("':json.result[i].").append(key).append(",");
                });
            }
            stringBuffer.append("                    });");
            stringBuffer.append("                }");
            stringBuffer.append("                return data;");
            stringBuffer.append("            }");
            stringBuffer.append("    }).on('onSetSelectValue', function (e, keyword) {");
            stringBuffer.append("        var refObj = $(this).attr('refId');");
            stringBuffer.append("        $(refObj).val(keyword.id);");
            stringBuffer.append("        let callback = $(this).attr('callback');");
            stringBuffer.append("        if (callback) {");
            stringBuffer.append("            if (!$.isFunction(callback)) {");
            stringBuffer.append("                eval('(' + callback + ')')");
            stringBuffer.append("            }");
            stringBuffer.append("        }");
            stringBuffer.append("    }).on('onUnsetSelectValue', function (e) {");
            stringBuffer.append("    });");
            stringBuffer.append("    $('.Clear").append(suggest).append("').on('click', function () {");
            stringBuffer.append("        var refObj = $(this).attr('refObj');");
            stringBuffer.append("        $(refObj).val('');");
            stringBuffer.append("        var refId = $(refObj).attr('refId');");
            stringBuffer.append("        $(refId).val('');");
            stringBuffer.append("       });");
            stringBuffer.append("    });");
            stringBuffer.append("</script>");
        }
        // 创建标签
        IModelFactory modelFactory = iTemplateContext.getModelFactory();
        IModel        model        = modelFactory.createModel();
        model.add(modelFactory.createText(stringBuffer.toString()));
        iElementTagStructureHandler.replaceWith(model, false);
    }

    private static StringBuffer arrayIdToString(JSONObject jsonobejct, StringBuffer sBuffer) {
        return sBuffer.append(jsonobejct).append(",");
    }
}
